//
//  EditViewController.m
//  MyGroupsCoreData
//
//  Created by Edward Knutson on 10/13/09.
//  Copyright Six Four Systems 2009. All rights reserved.
//

#import "EditViewController.h"
#import "Constants.h"

#import "MyGroupsAppDelegate.h"
#import "GroupViewController.h"
#import "Group.h"
#import "GroupDAO.h"
#import "Location.h"
#import "Tag.h"
#import "TransferGroup.h"

@implementation EditViewController

@synthesize dao, groupArray, groupCell, logoArray, managedObjectContext;

- (void)viewDidLoad {
    [super viewDidLoad];

	self.prefix = [FEED_PREFIX stringByAppendingString:GROUP_PREFIX];
	
	self.title = @"Groups";
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
	UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] 
									  initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh 
									  target:self action:@selector(loadOpml)];
	self.navigationItem.rightBarButtonItem = refreshButton;
	refreshButton.enabled = NO;	
	
	self.managedObjectContext = [(MyGroupsAppDelegate *)[[UIApplication sharedApplication]
													  delegate] managedObjectContext];
	self.dao = [[GroupDAO alloc] initWithContext:managedObjectContext];
	
		
	self.logoArray = [[NSMutableArray alloc] init];
	[logoArray release];
	
	self.statusMsg = @"No groups yet";
	[self initData];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	if(groupArray == nil || [groupArray count] == 0)
		[self loadOpml];
	else self.navigationItem.rightBarButtonItem.enabled = YES;
}


- (NSArray *)groups:(NSError **)error {
//	return [dao subscribedGroups:error];
	return [dao groups:error];
}

- (void)initData {
	NSLog(@"EVC:initData");
	NSError *error = nil;
	NSMutableArray *groupArr = [NSMutableArray alloc];
	NSArray *groups = [self groups:&error];
	NSLog(@"groups.count=%d", [groups count]);
	if(groups != nil && [groups count] > 0) {
		self.groupArray = [groupArr initWithArray:groups];
		[NSThread detachNewThreadSelector:@selector(loadLogos:) toTarget:self withObject:groups];
	}
	else self.groupArray = [groupArr init];
}

- (void)loadLogos:(id)groups {
	NSLog(@"EVC:loadLogos");
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
	for(int i=0; i<[groups count]; i++) {
		Group *group = [groups objectAtIndex:i];
		[logoArray addObject:[self loadImage:group.logoUrl]];
		[super processItems];
	}
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	[pool release];
}	

- (id)loadImage:(NSString *)url {
	NSLog(@"EVC:loadImage");
	if(url == nil)
		return [NSNull null];
	NSLog(@"\n\n\nloading logo from: %@\n\n\n", url);
	NSURL *imgUrl = [NSURL URLWithString:url];
	NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
	UIImage *logo = [UIImage imageWithData:imgData];
	if(logo == nil) {
		return [NSNull null];
	}
	return logo;
}


- (void)loadOpml {
	NSLog(@"EVC:loadOpml");
	self.feedUrl = GROUP_FEED_URL;
	[self loadFeed];
}
	
- (void)processItems {
	NSLog(@"EVC:processItems");
	NSError *error = nil;
	if(items != nil) {
		[groupArray removeAllObjects];
		[logoArray removeAllObjects];
		for(int i=0; i<[items count]; i++) {
			TransferGroup *xfer = [[TransferGroup alloc] initWithDictionary:[items objectAtIndex:i]];
			[dao saveGroup:xfer error:&error];
			if(error != nil)
				NSLog(@"error saving group: %@", error);
		}
	} else NSLog(@"items array is nil");
	[self initData];
	[super processItems];
	self.navigationItem.rightBarButtonItem.enabled = YES;
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
	// Release anything that can be recreated in viewDidLoad or on demand.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if(groupArray == nil)
		return 1;
	return [groupArray count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = nil;
    static NSString *GenericCellIdentifier = @"GenericCell";
    if([groupArray count] == 0) {
		cell = [tableView dequeueReusableCellWithIdentifier:GenericCellIdentifier];
		if (cell == nil) {			
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:GenericCellIdentifier] autorelease];
//			[cell release];
		}
		
		cell.textLabel.text = statusMsg;
		return cell;
	}
    
	static NSString *GroupCellIdentifier = @"GroupCell";
    
    cell = [tableView dequeueReusableCellWithIdentifier:GroupCellIdentifier];
	if (cell == nil) {
		[[NSBundle mainBundle] loadNibNamed:@"GroupCell" owner:self options:nil];
        cell = groupCell;
        self.groupCell = nil;
	}
    
	Group *group = [groupArray objectAtIndex:indexPath.row];
	
	// Tag 1: Name
	UILabel *label = (UILabel *)[cell viewWithTag:1];
	label.text = group.name;
	
	// Tag 2: Description
	label = (UILabel *)[cell viewWithTag:2];
	label.text = group.groupDescription;

	// Tag 3: Logo
	if(logoArray == nil || indexPath.row >= [logoArray count])
		return cell;
	
	id logo = [logoArray objectAtIndex:indexPath.row];
	if(![[NSNull null] isEqual:logo]) {
		UIImageView *logoView = (UIImageView *)[cell viewWithTag:3];
		logoView.image = logo;
	}

	return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 120.0;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here -- for example, create and push another view controller.
    // NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath];
    // Pass the selected object to the new view controller.
    /// ...
	GroupViewController *anotherViewController = [[[GroupViewController alloc] initWithNibName:@"GroupViewController" bundle:nil] autorelease];
	TransferGroup *xfer = [[TransferGroup alloc] initWithGroup:[groupArray objectAtIndex:indexPath.row]];
	anotherViewController.group = xfer;
	[xfer release];
	//[anotherViewController.group release];
	if(indexPath.row < [logoArray count]) {
		anotherViewController.logo = [logoArray objectAtIndex:indexPath.row];
	} else anotherViewController.logo = [NSNull null];
	[self.navigationController pushViewController:anotherViewController animated:YES];
	
}


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
		int row = indexPath.row;
		
        // Delete the managed object for the given index path
		[(Group *)[groupArray objectAtIndex:row] setSubscribed:[NSNumber numberWithBool:NO]];
		
		// Save the context.
		NSError *error;
		if (![managedObjectContext save:&error]) {
			// Handle the error...
		}
		
		[groupArray removeObjectAtIndex:row];
		[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
}


- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // The table view should not be re-orderable.
    return NO;
}


- (void)dealloc {
	[managedObjectContext release];
	[dao release];
	[groupArray release];
	[logoArray release];
//	[groupCell release];
    [super dealloc];
}


@end

